package com.example.leetcode.common;

/**
 * @author zhanpengguo
 * @date 2019-08-15 15:29
 */
public class TreeOperate {

    /**
     * 创建排序二叉树
     * @param ints
     * @return
     */
    public static TreeNode create(int[] ints) {
        TreeNode treeNode = new TreeNode(ints[0]);
        for (int i = 1; i < ints.length; i++) {
            insert(treeNode, ints[i]);
        }
        return treeNode;
    }

    private static void insert(TreeNode treeNode, int node) {
        int val = treeNode.val;
        TreeNode currentNode = new TreeNode(node);
        if (node <= val) {
            if (treeNode.left == null) {
                treeNode.left = currentNode;
            } else {
                insert(treeNode.left, node);
            }
        } else {
            if (treeNode.right == null) {
                treeNode.right = currentNode;
            } else {
                insert(treeNode.right,node);
            }
        }
    }

    /**
     * 创建普通二叉树
     * @param ints
     * @return
     */
    public static TreeNode create1(int[] ints) {
        TreeNode treeNode = new TreeNode(ints[0]);
        for (int i = 1; i < ints.length; i++) {
            insert1(treeNode, ints[i]);
        }
        return treeNode;
    }

    private static void insert1(TreeNode treeNode, int node) {
        TreeNode currentNode = new TreeNode(node);
        if (treeNode.left == null) {
            treeNode.left = currentNode;
        } else if (treeNode.right == null) {
            treeNode.right = currentNode;
        } else if (treeNode.left.left == null || treeNode.left.right == null) {
            insert1(treeNode.left, node);
        } else {
            insert1(treeNode.right,node);
        }
    }

    /**
     * 前序遍历
     * @param treeNode
     */
    public static void preOrder(TreeNode treeNode) {
        if (treeNode != null) {
            System.out.println(treeNode.val);
            preOrder(treeNode.left);
            preOrder(treeNode.right);
        }
    }
    /**
     * 中序遍历
     * @param treeNode
     */
    public static void midOrder(TreeNode treeNode) {
        if (treeNode != null) {
            preOrder(treeNode.left);
            System.out.println(treeNode.val);
            preOrder(treeNode.right);
        }
    }
    /**
     * 后序遍历
     * @param treeNode
     */
    public static void aftOrder(TreeNode treeNode) {
        if (treeNode != null) {
            preOrder(treeNode.left);
            preOrder(treeNode.right);
            System.out.println(treeNode.val);
        }
    }

    public static void main(String[] args) {
        int[] ints = {2, 1, 3, 4, 7};
        TreeNode treeNode = create1(ints);
        preOrder(treeNode);
//        System.out.println();
//        midOrder(treeNode);
//        System.out.println();
//        aftOrder(treeNode);
    }
}
